<?php

namespace Apps\Common\Pay;

use Apps\App\Models\PayAttach;
use Deyi\Alipay\lib\AlipayCore;
use Vendor\WeixinPay\WeixinPay;

Trait PayTrait
{
    //支付宝支付方式
    public function alipay($goodsId, $subject, $out_trade_no, $total_fee, $body, $notifyUrl)
    {
        $partner = $this->getDI()->get('config')->alipay->partner; //合作身份者id
        $inputCharset = $this->getDI()->get('config')->alipay->inputcharset;
        $signType = $this->getDI()->get('config')->alipay->signtype;
        $sellerId = $this->getDI()->get('config')->alipay->sellerid; //支付宝账号

        $ali = [
            'service' => 'mobile.securitypay.pay',
            'partner' => $partner,
            '_input_charset' => $inputCharset,
            'sign_type' => $signType,
            'sign' => '',
            'notify_url' => urlencode($notifyUrl), //回调地址
            'out_trade_no' => $out_trade_no, //商户网站唯一订单号
            'subject' => $subject, //商品名称
            'payment_type' => 1, //支付类型
            'seller_id' => $sellerId,
            'total_fee' => $total_fee, //总金额
            'body' => $body, //商品详情
            'count' => 1,
            'goods_id' => $goodsId
        ];
        $ali = AlipayCore::argSort($ali);
        $str = '';

        foreach ($ali as $key => $val) {
            if (!in_array($key, ['sign_type', 'sign'])) {
                $val = '"' . $val . '"';
                $str .= (('' == $str) ? '' : '&') . "{$key}={$val}";
            }
        }
        $sign = mb_convert_encoding(urlencode($this->sign($str)), 'UTF8');
        $str .= '&sign=' . '"' . $sign . '"' . '&sign_type=' . '"' . $ali['sign_type'] . '"';//传给支付宝接口的数据

        return $str;
    }

    //微信支付方式
    public function weixinpay($body, $out_trade_no, $total_fee, $attach, $notifyUrl)
    {
        $appKey = $this->getDI()->get('config')->weixinpay->appkey;
        $appId = $this->getDI()->get('config')->weixinpay->appid;     //appid
        $partner = $this->getDI()->get('config')->weixinpay->partner;    //财付通商户号

        //获取提交的订单号
        $outparams = [];
        $time_stamp = time();
        $nonce_str = md5(mt_rand());
        $attach = PayAttach::getInstance()->addAndReturnId($attach);
        $prepayid = WeixinPay::getPrePayId($appId, $partner, $appKey, md5(mt_rand() . uniqid()), $body, $attach, $out_trade_no, $total_fee, $notifyUrl);

        if ($prepayid) {
            $pack = 'Sign=WXPay';
            //输出参数列表
            //生成签名
            $prePaySign = WeixinPay::createAppPayPreSign([
                'appid' => $appId,
                'noncestr' => $nonce_str,
                'package' => $pack,
                'partnerid' => $partner,
                'prepayid' => $prepayid,
                'timestamp' => $time_stamp
            ], $appKey);

            $outparams = [
                'retcode' => 0,
                'retmsg' => 'ok',
                'appid' => $appId,
                'noncestr' => $nonce_str,
                'package' => $pack,
                'prepayid' => $prepayid,
                'timestamp' => $time_stamp,
                'sign' => $prePaySign,
            ];

        } else {
            $outparams = [
                'retcode' => -2,
                'retmsg' => '错误：获取prepayId失败',
            ];
        }

        return $outparams;
    }

    //RSA签名
    public function sign($data)
    {
        //读取私钥文件
        $priKey = file_get_contents(dirname($_SERVER['DOCUMENT_ROOT']) . '/lib/deyi/Alipay/key/rsa_private_key.pem');//私钥文件路径
        $res = openssl_get_privatekey($priKey); //转换为openssl密钥，必须是没有经过pkcs8转换的私钥
        openssl_sign($data, $sign, $res); //调用openssl内置签名方法，生成签名$sign
        openssl_free_key($res); //释放资源
        $sign = base64_encode($sign); //base64编码

        return $sign;

    }


}
